const express = require('express');
const router = express.Router();
const db = require('../../../util/dbConfig/dbConfig')
const multer = require("multer")
const path = require("path")

let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.resolve(__dirname,"../../../public/images/sheepFace"))
    },
    filename: function (req, file, cb) {
        let typeIndex = [
            'image/gif','image/jpeg','image/png'
        ].indexOf(file.mimetype)
        if(typeIndex === -1){
            cb(new Error("文件格式不正确"))
            return
        }
        let ext = ['.gif','.jpg','.png'][typeIndex]
        cb(null, file.fieldname + '-' + Date.now() + ext)
    }
})

let upload = multer({ storage }).single('avatar')

//图片上传
router.post('/uploadFace',async (req,res) => {
    console.log('上传开始');
    // if(req.session.userInfo.admin !== 1 || !req.session.userInfo){
    //     return res.send({
    //         code: 3,
    //         msg: '非管理员权限或未登录'
    //     })
    // }
    let {sheepId} = req.body
    console.log(req.body);
    if(!sheepId){
        return res.send({
            code: 1,
            msg: '参数错误'
        })
    }
    upload(req,res,async function (err){
        if(err instanceof multer.MulterError){
            return res.send({
                code: 1,
                msg: "上传组件错误"
            })
        }else if (err){
            return res.send({
                code: 2,
                msg: "上传时出现了一个未知错误"
            })
        }
        //上传完成 没有错误
        console.log(req.file);
        try{
            //let _id = req.session.userInfo._id
            //修改数据库
            let face = '/face/'+req.file.filename
            let sqlUpdate = `update sheep set PICTURE=? where ID=?`
            let sqlUpdateArr = [face,sheepId]
            let result = await db.SySqlConnect(sqlUpdate,sqlUpdateArr)
            console.log(result);
            return res.send({
                code: 0,
                msg: "图片上传成功"
            })
        }catch (e) {
            console.log(e);
            return res.send({
                code: 4,
                msg: "服务器错误，请稍后重试"
            })
        }

    })
})

module.exports = router
